package com.system.pay.controller;

import java.util.Iterator;
import com.alipay.api.AlipayApiException;
import com.system.pay.bean.PayBean;
import com.system.pay.dto.QueryDTO;
import com.system.pay.dto.RefundDTO;
import com.system.pay.service.PayService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @className: PayController
 * @description: TODO 类描述
 * @author: Li Chuanwei
 * @date: 2023/12/03 9:22
 * @Company: Copyright [日期] by [作者或个人]
 **/
@RestController
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private PayService payService;

    /**
     * 阿里支付
     * @param alipayBean
     * @return
     * @throws AlipayApiException
     */
    @PostMapping("/alipay")
    public Map alipay(@RequestBody PayBean alipayBean) throws AlipayApiException {
        System.out.println(alipayBean);
        Map<String,Object> map = new HashMap<String,Object>();

        String str = payService.Pay(alipayBean);
        System.out.println(str);
        map.put("msg",str);
        map.put("code",0);
//
        return map;
    }

    @RequestMapping("/payNotify")
    @ResponseBody
    public String payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
//		String requestJson = IOUtils.toString(request.getInputStream(), "utf-8");
//		logger.info("支付宝支付结果通知接口请求数据json:" + requestJson);
        try {
            java.util.Enumeration enu=request.getParameterNames();
            while(enu.hasMoreElements()){
                String paraName=(String)enu.nextElement();
                System.out.println(paraName+": "+request.getParameter(paraName));
            }
        } catch (Exception e4) {
            e4.printStackTrace();
            return "fail";
        }

        //获取支付宝POST过来反馈信息
        Map<String,String> receiveMap = getReceiveMap(request);
        System.out.println("支付宝支付回调参数:" + receiveMap);
        boolean signVerified = false;
        try{
            signVerified = payService.paynotify(receiveMap);
            System.out.println("支付宝支付结果通知接口响应数据json:" + signVerified);
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("支付宝支付结果通知接口服务端异常,异常信息---" + e.getMessage());
            return "fail";
        }
        if(signVerified){
            return "success";
        }else{
            return "fail";
        }
    }

    @PostMapping("/getResult")
    public Integer getResult(@RequestBody QueryDTO queryDTO) throws Exception {
        return payService.getResult(queryDTO.getOut_trade_no());
    }

    private static Map<String,String> getReceiveMap(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        return params;
    }

    @PostMapping("/appointmentRefund")
    public boolean appointmentRefund(@RequestBody RefundDTO refundDTO) throws Exception {
        return payService.appointmentRefund(refundDTO);
    }
}